function ShowMsg(msg) {
    layer.msg(msg);
}

function ShowSuccess(msg) {
	layer.msg(msg);
}

function ShowFailure(msg) {
	layer.msg(msg);
}

function ShowWarn(msg, $focus, clear) {
	layer.msg(msg);
}

function layerLoading(msg){
	return layer.msg(msg, {shade:0.00001,icon: 16,time: 1000*60*10 });
}

  function infoMsg(msg){
	  layer.msg(msg);
  }
  function sucMsg(msg){
	  layer.msg(msg);
  }
  function errMsg(msg){
	  layer.msg(msg);
  }
  
  function confirm(msg,callback){
		//询问框
		  layer.confirm(msg, {
		    btn: ['确定','取消'] //按钮
		  }, callback,
		  function(index){
			  layer.close(index);
		  });
	  }


var ps = 15;


var pn = 1;
var qs = 0;
var total = 0;
var nowPageTotal = 0;
//是否有操作列
var isOper = true;
//是否有复选列
var isCheckbox = true;


/***
 * 获取分页参数
 * @param datagrid
 * @returns {Array}
 */
function getPageParams(){
	var pageParams = new Array();
	pageParams.push({name:'pageNum',value:pn});
	pageParams.push({name:'pageSize',value:ps});
	return pageParams;
}

/***
 * 获取datagrid自定义参数
 * @param datagrid
 * @returns Array json数组
 */
function getArgsParams(datagrid){
	var dataArgs = datagrid.attr("dataArgs");
	
	var params = new Array();
	if(undefined != dataArgs && "" != dataArgs){
		params = eval("(["+dataArgs+"])");
	}
	return params;
}

/***
 * 获取排序参数
 * @param datagrid
 * @returns Array json数组
 */
function getSortsParams(datagridId){
	var toolbar = $(".toolbar[casedatagrid='"+datagridId+"']");
	var btns = toolbar.find(".sff_an.sortbtn");
	var params = new Array();
	if(btns.length>0){
		btns.each(function(i){
			var sort = $(this).attr("sort");
			var field = $(this).attr("field");
			params.push({name:"feilds["+i+"].sort",value:sort});
			params.push({name:"feilds["+i+"].name",value:field});
		});
	}
	return params;
}

function trimFormArray(arrs){
	var arrsx = [];
	if(null != arrs && arrs.length > 0){
		for (var i = 0; i < arrs.length; i++) {
			arrsx.push({name:arrs[i].name,value:$.trim(arrs[i].value)});
		}
	}
	return arrsx;
}



/***
 * 获取form查询表单参数
 * @param queryForm
 * @returns
 */
function getFormParams(queryForm){
	if(queryForm.length>0){
		var arrs = trimFormArray(queryForm.serializeArray());
		arrs.push({name:"qs",value:qs});
		return arrs;
	}
	return null;
}


function getFormParamsUrls(queryForm){
	if(queryForm.length>0){
		var arrs = queryForm.serializeArray();
		if(null != arrs && arrs.length > 0){
			var psx = [];
			for (var i = 0; i < arrs.length; i++) {
				psx.push(arrs[i].name+"="+$.trim(arrs[i].value));
			}
			return psx.join("&");
		}
	}
	return "";
}

/***
 * 绑定查询表单
 */
function bindForm(queryForm,datagridid){
	queryForm.submit(function(){
		pn = 1;
		qs = 1;
		datagrid(datagridid);
		return false;
	});
	
	queryForm.find(".reset").click(function(){
		queryForm[0].reset();
		pn = 1;
		qs = 1;
		datagrid(datagridid);
		return false;
	});
}

function initPageDom(){
	$(":checkbox[name='allchk']").prop("checked",false);
	var psx = $("#datagrid").attr("pageSize");
	if(null != psx && undefined != psx){
		ps = psx;
	}
}

/***
 * 初始化datagrid组件
 * @param datagridid 组件ID
 * @param formArgs 组件对应查询表单参数
 */
function datagrid(datagridid,pageParams,argsParams,formParams,sortsParams){
	initPageDom();
	var datagrid = $("#"+datagridid);
	var queryForm = $(".queryForm[casedatagrid='"+datagridid+"']");
	var params = new Array;
	if(arguments.length == 1){
		params = getPageParams().concat(getArgsParams(datagrid)).concat(getFormParams(queryForm));
		var sps = getSortsParams(datagridid);
		if(null != sps && sps.length>0){
			params = params.concat(sps);
		}
	}
	if (arguments.length == 2) {
		params = pageParams;
	}
	if (arguments.length == 3) {
		params = pageParams.concat(argsParams);
	}
	if (arguments.length == 4) {
		params = pageParams.concat(argsParams).concat(formParams);
	}
	if (arguments.length == 5) {
		if(null != sortsParams && sortsParams.length>0){
			params = pageParams.concat(argsParams).concat(formParams).concat(sortsParams);
		}else{
			params = pageParams.concat(argsParams).concat(formParams);
		}
	}
	
	var datasource = datagrid.attr("datasource");
	
	var loadingIndex = layer.msg('加载中,请稍后..', {shade:0.00001,icon: 16,time: 1000*60*10 });
	$.ajax({type:"POST",url:datasource,data:params,dataType:"json",success:function(data){
		   if(data.logout){
			   layer.alert("登陆失效，请重新登陆",{closeBtn:false},function(){
				   location.href = "login";
			   });
			   return false;
		   }
		   bindData(datagrid,data.rows);
		   bindJsonData(data.jsonParams);
		   total = data.total;
		   nowPageTotal = data.rows.length;
		   pageBarLoad(datagridid,data.pageSize,data.pageNum);
		   layer.close(loadingIndex);
		   
		   bindCheckBox();
		   
		},error:function(){
		   //alert("数据加载异常");
		   layer.close(loadingIndex);
		   errMsg("加载数据失败");
		}});
	
}

function bindJsonData(jsonParams){
	if(null != jsonParams){
		for(var key in jsonParams){
			$("#"+key).text(jsonParams[key]);
		}
	}else{
		var dataDoms = $(".bind-data");
		if(dataDoms.length > 0){
			dataDoms.each(function(){
				$(this).text($(this).attr("default"));
			});
		}
	}
}
function bindDrag(datagrid){
	var isDrag = datagrid.attr("isDrag");
	
	if("true" != isDrag || !isDrag){
		return false;
	}
	var dragAction = datagrid.attr("dragAction");
	var keyFeild = datagrid.attr("keyFeild");
	
	var fixHelperModified = function(e, tr) {
        var $originals = tr.children();
        var $helper = tr.clone();
        $helper.children().each(function(index) {
            $(this).width($originals.eq(index).width())
        });
        return $helper;
    },
    updateIndex = function(e, ui) {
        $('td.index', ui.item.parent()).each(function (i) {
            $(this).html(i + 1);
        });
    };
    
    //初始化信息类型table的拖拽排序
    	$("#datagridTbody").sortable({
            helper: fixHelperModified,
            stop: updateIndex,
            update: function(event, ui) { 
            	var trs = $("#datagridTbody").find("tr");
            	if(trs.length > 0){
            		var ids = [];
            		trs.each(function(i){
            			ids.push($(this).attr("data-id"));
            			$(this).text(i+1);
            		});
            		ajax(dragAction+"?"+keyFeild+"="+ids.join("&"+keyFeild+"="),function(data){
            		});
            	}
            	
            } 
        }).disableSelection();
}

function getAligns(datagrid){
	var tds = datagrid.find("tr:first>th");
	var aligns = new Array();
	tds.each(function(i){
		aligns.push({align:toNUll($(this).attr("align"))});
	});
	return aligns;
}
function getFeilds(datagrid){
	var tds = datagrid.find("tr:first>th");
	var feilds = new Array();
	var len = tds.length;
	
	var notTd = [];
	
	if(isCheckbox){
		notTd.push(0);
		notTd.push(1);
	}else{
		notTd.push(0);
	}
	if(isOper){
		notTd.push(len-1);
	}
	tds.each(function(i){
		if($.inArray(i,notTd) == -1){
			var feildButton = toNUll($(this).attr("feildButton"));
			if(null != feildButton){
				feildButton = eval("("+feildButton+")");
			}
			var spanClass = $(this).attr("spanClass");
			if("" == spanClass || undefined == spanClass || "undefined" == spanClass){
				spanClass = null;
			}
			feilds.push({feild:toNUll($(this).attr("feild")),spanClass:spanClass,feildButton:feildButton});
		}
	});
	return feilds;
}

function getButtons(datagrid){
	var buttons = datagrid.find("tr:first").find("th:last").attr("buttons");
	if(undefined != buttons && "" != buttons && null != buttons){
		buttons = eval("(["+buttons+"])");
	}
	return buttons;
}

function toNUll(str){
	if(undefined != str && "" != str && null != str){
		return str;
	}
	return null;
}


function initTds(feilds,row,aligns){
	var tds = new Array();
	for ( var i = 0; i < feilds.length; i++) {
		var feild = feilds[i];
		var feildName = feild.feild;
		var feildButton = feild.feildButton;
		
		//是否添加span样式
		var spanClass = feild.spanClass;
		
		var feildValue = row[feildName];
		if(null == feildValue){
			feildValue = "";
		}
		
		if(null != feildButton){
			var args = getButtonArgs(feildButton.feilds,null,row);
			var url = feildButton.url + (feildButton.url.indexOf("?")==-1?"?":"&") + args;
			var type = feildButton.type;
			var isNum = feildButton.isNum;
			
			if(isNum && parseInt(feildValue) == 0){
				feildValue = feildValue;
			}else{
				var fontSize = 14;
				if(isNum){
					fontSize = 16;
				}
				
				if('dialog' == type){
	        		var dialogType = "dialog";
					feildValue = '<a href="javascript:void(0);" style="font-size:'+fontSize+'px;font-weight:600;" class="blue bold" onclick="javascript:top.'+dialogType+'(\''+feildButton.title+'\',\''+url+'\',\''+feildButton.width+'\',\''+feildButton.height+'\');">'+feildValue+'</a>';
				}
				if('url' == type){
					var target = '';
					if(1 == feildButton.target){
						target = 'target="_blank"';
					}
					feildValue = '<a href="'+url+'" style="font-size:'+fontSize+'px;font-weight:600;" '+target+'>'+feildValue+'</a>';
				}
				if('img' == type && null != feildValue && "" != feildValue){
					feildValue = '<a href="'+feildValue+'" style="font-size:'+fontSize+'px;font-weight:600;" target="_blank" class="blue bold"><img src="'+feildValue+'" style="width:'+feildButton.width+';height:'+feildButton.height+';"/></a>';
				}
			}
		}else{
			if(("" != feildValue || parseInt(feildValue) == 0) && "" != spanClass){
				feildValue = '<span class="'+spanClass+'">'+feildValue+'</span>';
			}
		}
		tds.push('<td '+setAligns(aligns[i+1].align)+'>'+feildValue+'</td>');
	}
	return tds.join("");
}
function initButtons(buttons,row,permissionIds){
	var btns = new Array();
	
	for ( var i = 0; i < buttons.length; i++) {
		var button = buttons[i];
		
		var authId = button.authId;
		if(undefined != authId && "undefined" != authId && "" != authId && null != authId){
			if(null == permissionIds || -1 == permissionIds.indexOf(","+authId+",")){
				//top.showWan("无权限进行此操作！");
				continue;
			}
		}
		
		var args = getButtonArgs(button.feilds,button.otherParams,row);
		var url = button.url + (button.url.indexOf("?")==-1?"?":"&") + args;
		
		//是否启用查询表单参数
		/*var formParams = button.formParams;
		if(formParams){
			var fps = getFormParamsUrls($(".queryForm"));
			if("" != fps && null != fps){
				url = url.indexOf("?")==-1?"?":"&" + fps;
			}
		}*/
		
		var btnClass = button.btnClass;
		//btnClass = btnClass == 'edit'?'submit':'error';
		
		//按钮是否显示
		var isShow = true;
		var enable = button.enable;
		if(null != enable){
			var feilds = enable[0];
			var feildValues = enable[1];
			for (var j = 0; j < feilds.length; j++) {
				if(row[feilds[j]] != feildValues[j]){
					isShow = false;
				}
			}
		}
		
		
		var parentStr = "";
		if(button.parent){
			parentStr = "parent.";
		}
		
		var iconSpan = '';
		if(button.icon && '' != button.icon){
			iconSpan = '<span class="'+button.icon+'"></span>';
		}
		
		if(isShow){
			if(button.type == "dialog"){
				var dialogType = "dialog";
				
        		var ajaxValidate = button.ajaxValidate;
        		if(undefined != ajaxValidate && null != ajaxValidate && "" != ajaxValidate){
        			var validateUrl = ajaxValidate;
            		
            		var isParent = parentStr == 'parent.';
        			
        			btns.push('<a href="javascript:;" class=" '+btnClass+'" onclick="ajaxValidateForDialog(\''+validateUrl+'\',\''+args+'\',\''+url+'\',\''+button.title+'\',\''+button.width+'\',\''+button.height+'\','+isParent+')">'+iconSpan + ' '+button.text+'</a>');
        		}else{
        			btns.push('<a href="javascript:;" class=" '+btnClass+'" onclick="top.'+dialogType+'(\''+button.title+'\',\''+url+'\',\''+button.width+'\',\''+button.height+'\')">'+iconSpan + ' '+button.text+'</a>');
        		}
			}
			if(button.type == "url"){
				var target = '';
				if(1 == button.target){
					target = ' target="_blank"';
				}
        			btns.push('<a href="'+url+'" '+target+' class=" '+btnClass+'">'+iconSpan + ' '+button.text+'</a>');
			}
	        if(button.type == "ajax"){
	        	//删除操作
	        	if(button.method == "dels"){
	        		btns.push('<a href="javascript:;" class=" '+btnClass+'" onclick="'+button.method+'(\''+button.url+'\',\''+args+'\')">'+iconSpan + ' '+button.text+'</a>');
	        	}
	        	//常规ajax操作
	        	if(button.method == "common"){
	        		var isConfirm = true;
	        		if(undefined != button.isConfirm && null != button.isConfirm){
	        			isConfirm = button.isConfirm;
	        		}
	        		var confirmType = 'confirm';
	        		if(undefined != button.confirmType && null != button.confirmType){
	        			confirmType = button.confirm;
	        		}
	        		btns.push('<a href="javascript:;" class=" '+btnClass+'" onclick="'+button.method+'(\''+button.url+'\',\''+args+'\',\''+button.text+'\','+isConfirm+',\''+confirmType+'\')">'+iconSpan + ' '+button.text+'</a>');
	        	}
			}
	        
	        if(button.type == "click"){
	        	btns.push('<a href="javascript:;" class=" '+btnClass+'" json=\''+JSON.stringify(row)+'\' onclick="'+button.method+'(this)">'+iconSpan + ' '+button.text+'</a>');
	        }
		}
	}
	return "<div class=\"am-btn-toolbar\"><div class=\"am-btn-group am-btn-group-xs\">" + btns.join("&nbsp;&nbsp;") + "</div></div>";
	
}

/***
 * 
 * @param buttonFeilds  字段参数
 * @param otherParams   其他参数
 * @param row           行记录
 * @returns 拼接参数   a=1&b=2&c=3..
 */
function getButtonArgs(buttonFeilds,otherParams,row){
	var args = new Array();
	for ( var i = 0; i < buttonFeilds.length; i++) {
		args.push(buttonFeilds[i]+"="+row[buttonFeilds[i]]);
	}
	
	if(null != otherParams){
		var names = otherParams[0];
		var values = otherParams[1];
		for (var j = 0; j < names.length; j++) {
			args.push(names[j]+"="+values[j]);
		}
	}
	return args.join("&");
}

/***
 * 绑定数据
 * @param datagrid
 * @param rows
 */
function bindData(datagrid,rows){
	var tbody = datagrid.find("tbody");
	tbody.empty();
	
	if(null == rows || rows.length == 0){
		return false;
	}
	
	//主键Id
	var keyFeild = datagrid.attr("keyFeild");
	//字段数组
	var feilds = getFeilds(datagrid);
	//操作按钮数组
	var buttons = getButtons(datagrid);
	
	var aligns = getAligns(datagrid);
	
	var permissionIds = datagrid.attr("permissionIds");
	if(undefined != permissionIds && null != permissionIds && "" != permissionIds){
		permissionIds = permissionIds;
	}else{
		permissionIds = null;
	}
	
	var trs = new Array();
	for(var i=0; i<rows.length; i++){
		var row = rows[i];
		
		var operTd = '';
		if(isOper){
			operTd = '<td '+setAligns(aligns[aligns.length-1].align)+'>'+initButtons(buttons,row,permissionIds)+'</td>';
		}
		
		var checkboxTd = '';
		if(isCheckbox){
			checkboxTd = '<td '+setAligns(aligns[aligns.length-1].align)+'><input type="checkbox" name="id" value="'+row[keyFeild]+'"/></td>';
		}
		
		var tr = '<tr '+((i+1)%2==0?'class="trS"':'')+' data-id="'+row[keyFeild]+'">'
			      +checkboxTd
			      +'<td '+setAligns(aligns[0].align)+'>'
			      +((i+1)+((pn-1)*ps))
			      +'</td>'
			      +initTds(feilds,row,aligns)
			      +operTd
			    +'</tr>';
		trs.push(tr);
	}
	tbody.append(trs.join(""));
	
	bindDrag(datagrid);
}

function setAligns(align){
	if(null != align && "" != align){
		return 'align="'+align+'"';
	}
	return '';
}

function go(datagridid,pageSize,pageNum){
	pn = pageNum;
	datagrid(datagridid);
}

function goNum(datagridid,pageSize,btn){
	var goX = $(btn).prev().val();
	if(null != goX && '' != goX){
		goX = parseInt(goX);
		go(datagridid,pageSize,goX);
	}
}

function getPageOptions(totalPage){
	var options = new Array();
	for ( var i = 1; i <= totalPage; i++) {
		options.push("<option value=\""+i+"\" "+(i==pn?"selected='selected'":"")+">"+i+"</option>");
	}
	return options.join("");
}

//function pageBarLoad(datagridid,pageSize,pageNum){
//	var pageBar = $(".page[casedatagrid='"+datagridid+"']");
//	if(pageBar.length <= 0){
//		return false;
//	}
//	var tdHtml = "未查询到相关数据";
//    if(total <= 0){
//    	pageBar.find("#pageMsg span").text(tdHtml);
//    	return false;
//    }
//    
//    pageBar.find("#pageMsg").hide();
//	//总页数
//	var totalPage = Math.ceil(total/pageSize);
//	
//	var startNums = (pageNum-1)*pageSize+1;
//	var endNums = startNums+nowPageTotal-1;
//	var leftInfo = '当前显示记录 '+startNums+' 到 '+endNums+'条，总记录数'+total;
//	
//	var rightInfo = "";
//	if(totalPage == 1){
//		rightInfo += '<li class="disabled"><a href="javascript:;">&laquo;</a></li>'
//	             +'<li class="disabled"><a href="javascript:;">1</a></li>'
//	             +'<li class="disabled"><a href="javascript:;">&raquo;</a></li>';
//		leftInfo = '总记录数'+total;
//    }else{
//		var preNum = pageNum -1==0?pageNum:pageNum-1;
//		var nextNum = pageNum +1>totalPage?totalPage:pageNum+1;
//		var options = getPageOptions(totalPage);
//		
//		if(pageNum < totalPage && pageNum > 1){
//			var numsLi = "";
//			for (var i = 1; i <= totalPage; i++) {
//				numsLi += '<li><a href="javascript:go(\''+datagridid+'\','+pageSize+','+i+');">'+i+'</a></li>';
//			}
//			
//			rightInfo += '<li><a href="javascript:go(\''+datagridid+'\','+pageSize+',1);">&laquo;</a></li>'
//	             + numsLi
//	             + '<li><a href="javascript:go(\''+datagridid+'\','+pageSize+','+totalPage+');">&raquo;</a></li>';
//		}
//		if(pageNum == 1){
//			var numsLi = "";
//			for (var i = 1; i <= totalPage; i++) {
//				numsLi += '<li><a href="javascript:go(\''+datagridid+'\','+pageSize+','+i+');">'+i+'</a></li>';
//			}
//			
//			rightInfo += '<li class="disabled"><a href="javascript:;">&laquo;</a></li>'
//	             + numsLi
//	             + '<li><a href="javascript:go(\''+datagridid+'\','+pageSize+','+totalPage+');">&raquo;</a></li>';
//		}
//        if(pageNum == totalPage){
//        	var numsLi = "";
//			for (var i = 1; i <= totalPage; i++) {
//				numsLi += '<li><a href="javascript:go(\''+datagridid+'\','+pageSize+','+i+');">'+i+'</a></li>';
//			}
//			
//			rightInfo += '<li><a href="javascript:go(\''+datagridid+'\','+pageSize+',1);">&laquo;</a></li>'
//	             + numsLi
//	             + '<li class="disabled"><a href="javascript;">&raquo;</a></li>';
//		}
//	}
//	pageBar.find("#pageLeft").empty().text(leftInfo);
//	pageBar.find(".pagination").empty().append(rightInfo);
//	pageBar.find("#pageLeft,#pageRight").show();
//}

function changeSize(a){
	ps = $(a).val();
	$("#currentSize").text(ps);
	go('datagrid',ps,1);
}

function pageBarLoad(datagridid,pageSize,pageNum){
	var pageBar = $(".page[casedatagrid='"+datagridid+"']");
	
	if(pageBar.length <= 0){
		return false;
	}
	var tdHtml = '<span>未查询到相关数据</span>';
    if(total <= 0){
    	pageBar.find(".pageLeft").html(tdHtml).show();
    	pageBar.find(".pageRight").hide();
    	return false;
    }
    
    pageBar.find(".pageLeft").hide();
	//总页数
	var totalPage = Math.ceil(total/pageSize);
	
	var startNums = (pageNum-1)*pageSize+1;
	var endNums = startNums+nowPageTotal-1;
	
	var leftInfo = 
	 '<ol class="am-breadcrumb"><li class="am-active">显示第 '+startNums+'到第 '+endNums+' 条记录，总共 '+total+'条记录，'+pageNum+'&nbsp;/'+totalPage+' </li> '
			+'<li class="am-active">每页显示 '
			+'<select onchange="changeSize(this)" style="width:50px;display: inline;">'
			+'<option value="10" '+(ps==10?'selected="selected"':'')+'>10</option>'
			+'<option value="15" '+(ps==15?'selected="selected"':'')+'>15</option>'
			+'<option value="25" '+(ps==25?'selected="selected"':'')+'>25</option>'
			+'<option value="50" '+(ps==50?'selected="selected"':'')+'>50</option>'
			+'<option value="100" '+(ps==100?'selected="selected"':'')+'>100</option>'
			+'</select>'
			+'  条记录'
			+'</li>';
	if(total == 0){
		leftInfo = "";
	}
	
	var rightInfo = '<li class="page-first"><a href="javascript:;" onclick="go(\''+datagridid+'\','+pageSize+',1)">«</a></li>';
	if(totalPage > 6){
		rightInfo += '<li class="page-number" data-page="1"><a href="javascript:;" onclick="go(\''+datagridid+'\','+pageSize+',1)">1</a></li>';
		if(pageNum <= 2){
			rightInfo += '<li class="page-number" data-page="2"><a href="javascript:;" onclick="go(\''+datagridid+'\','+pageSize+',2)">2</a></li>';
			rightInfo += '<li class="page-number" data-page="3"><a href="javascript:;" onclick="go(\''+datagridid+'\','+pageSize+',3)">3</a></li>';
	    	rightInfo += '<li class="page-number more"><a href="javascript:;">...</a></li>';
	    }else if(pageNum > 2 && pageNum <= totalPage-2){
	    	rightInfo += '<li class="page-number more"><a href="javascript:;">...</a></li>';
	    	
	    	rightInfo += '<li class="page-number" data-page="'+(pageNum-1)+'"><a href="javascript:;" onclick="go(\''+datagridid+'\','+pageSize+','+(pageNum-1)+')">'+(pageNum-1)+'</a></li>';
	    	rightInfo += '<li class="page-number" data-page="'+pageNum+'"><a href="javascript:;" onclick="go(\''+datagridid+'\','+pageSize+','+pageNum+')">'+pageNum+'</a></li>';
	    	rightInfo += '<li class="page-number" data-page="'+(pageNum+1)+'"><a href="javascript:;" onclick="go(\''+datagridid+'\','+pageSize+','+(pageNum+1)+')">'+(pageNum+1)+'</a></li>';
	    	rightInfo += '<li class="page-number more"><a href="javascript:;">...</a></li>';
	    }else{
	    	rightInfo += '<li class="page-number more"><a href="javascript:;">...</a></li>';
	    	for (var i = totalPage-2; i < totalPage; i++) {
	    		rightInfo += '<li class="page-number" data-page="'+i+'"><a href="javascript:;" onclick="go(\''+datagridid+'\','+pageSize+','+i+')">'+i+'</a></li>';
			}
	    }
	    rightInfo += '<li class="page-number" data-page="'+totalPage+'"><a href="javascript:;" onclick="go(\''+datagridid+'\','+pageSize+','+totalPage+');">'+totalPage+'</a></li>';
	}else{
		for (var i = 1; i <= totalPage; i++) {
			rightInfo += '<li class="page-number" data-page="'+i+'"><a href="javascript:;" onclick="go(\''+datagridid+'\','+pageSize+','+i+');">'+i+'</a></li>';
		}
	}
	
	rightInfo += '<li class="page-last"><a href="javascript:;" onclick="go(\''+datagridid+'\','+pageSize+','+totalPage+');">»</a></li>';
	
	rightInfo += '跳至<input type="text" class="form-control" style="width:50px;display:inline;padding:13px 3px;"><input type="button" style="padding:0.5em 0.4em;margin-bottom:2px;" class=" am-btn am-btn-primary am-btn-xs am-radius" onclick="goNum(\''+datagridid+'\',\''+pageSize+'\',this)" value="确定"/>'
	pageBar.find(".pageLeft").empty().append(leftInfo);
	pageBar.find(".tpl-pagination").empty().append(rightInfo);
	pageBar.find(".pageLeft,.pageRight").show();
	
	
	if(pageNum == 1){
		$(".page-first").addClass("am-disabled").find("a").removeAttr("onclick");
	}
    if(pageNum == totalPage){
		$(".page-last").addClass("am-disabled").find("a").removeAttr("onclick");
	}
    $('li[data-page="' + pageNum + '"]').addClass('am-active').find("a").removeAttr("onclick");
}

function getPageArr(pageNum,pageCount){
	var arrs = [];
	switch(pageNum){
		case 1:
			arrs = [1,1];
		break;
		case 2:
			arrs = [1,2];
		break;
		case 3:
			arrs = [1,3];
		break;
		case 4:
			arrs = [1,4];
		break;
		case 5:
			arrs = [1,5];
		break;
		case pageCount-1:
			arrs = [pageCount-4,pageCount];
		break;
		case pageCount:
			arrs = [pageCount-4,pageCount];
		break;
		default:
			arrs = [pageNum-2,pageNum+2];
		break;
	}
	return arrs;
}

function bindSortBar(toolbar,datagridId){
	var sortBtns = toolbar.find(".sortbtn");
	sortBtns.each(function(){
		var sortBtn = $(this);
		sortBtn.click(function(){
			var sort = sortBtn.attr("sort");
			if("default" == sort){
				sortBtn.attr("sort","asc").attr("class","sff_an sortbtn")
				       .find("img").attr("src","images/jt.jpg").show();
			}else if("asc" == sort){
				sortBtn.attr("sort","desc").attr("class","sff_an sortbtn")
			       .find("img").attr("src","images/jt2.jpg").show();
			}else{
				sortBtn.attr("sort","default").attr("class","s_an sortbtn")
			       .find("img").hide();
			}
			
			sortBtn.siblings(".sortbtn").attr("sort","default")
			                            .attr("class","s_an sortbtn")
			                            .find("img").hide();
			datagrid(datagridId);
		});
	});
}

function bindCheckBox(){
	$(":checkbox[name='allchk']").click(function(){
		var flag = $(this).prop("checked");
		$(":checkbox[name='id']").prop("checked",flag);
		if(flag){
			$("#xz").show();
			$(":checkbox[name='id']").parent().parent().addClass("trSelected");
		}else{
			$("#xz").hide();
			$(":checkbox[name='id']").parent().parent().removeClass("trSelected");
		}
	});
	
	$(":checkbox[name='id']").click(function(){
			var checked = $(this).prop("checked");
			if(checked){
				$(this).parent().parent().addClass("trSelected");
			}else{
				$(this).parent().parent().removeClass("trSelected");
			}
	});
	
	$("#xzsy").click(function(){
		var text = $("#xzsy").text();
		if(text == "勾选全部数据"){
			$("#sytitle").show();
			$("#xzsy").text("取消勾选全部数据");
			$("#xzz").val(1);
			$(":checkbox[name='allchk']").prop("checked",true);
			$(":checkbox[name='id']").prop("checked",true);
		}else{
			$("#sytitle").hide();
			$("#xzsy").text("勾选全部数据");
			$("#xzz").val(0);
			$(":checkbox[name='allchk']").prop("checked",false);
			$(":checkbox[name='id']").prop("checked",false);
		}
	});
}

$(function(){
	var datagrids = $(".datagrid");
	if(datagrids.length <= 0){
		return false;
	}
	
	
	var datagridId = "datagrid";
	var dataGrid = $("#"+datagridId)
	var psx = dataGrid.attr("pageSize");
	if(null != psx && undefined != psx){
		ps = psx;
	}
	isOper = dataGrid.find(".oper").length>0;
	isCheckbox = dataGrid.find(".checkbox").length>0;
	
	
	var queryForm = $(".queryForm[casedatagrid='"+datagridId+"']");
	var toolbar = $(".toolbar[casedatagrid='"+datagridId+"']");
	datagrid(datagridId);
	bindForm(queryForm,datagridId);
	bindSortBar(toolbar,datagridId);
	
	
	var permissionIds = $("#"+datagridId).attr("permissionIds");
	if(undefined != permissionIds && null != permissionIds && "" != permissionIds){
		permissionIds = permissionIds;
	}else{
		permissionIds = null;
	}
	
	var authBtns = $(".authBtn");
	if(authBtns.length > 0){
		authBtns.each(function(){
			var auth_id = $(this).attr("auth-id");
			if(null == permissionIds || -1 == permissionIds.indexOf(","+auth_id+",")){
				$(this).hide();
			}else{
				$(this).show();
			}
		});
	}
	
	$(".glyphicon-search").click(function(){
		queryForm.submit();
	});
	//bindCheckBox();
	
	
	
});

function refreshDatagrid(datagridId){
	var datagridId = "datagrid";
	datagrid(datagridId);
}

function ajax(url,callback){
	$.ajax({
		type:"POST", 
		url:url,
		data:"",
		dataType:"json",
		error:function(){ShowWarn("服务连接异常..");}, 
		success:callback
	});
}
function ajaxAsyncFalse(url,callback,completeBack){
	$.ajax({
		type:"POST", 
		url:url,
		async:false,
		data:"",
		dataType:"json",
		error:function(){ShowWarn("服务连接异常..");}, 
		success:callback,
		complete:completeBack
	});
}

function getCheckedIds(){
	var keyFeild = $("#datagrid").attr("keyFeild");
	return $(":checkbox[name='id']").serialize().replace(/id=/g,keyFeild+"=");
}

function dels(url,params){
	if (arguments.length == 1) {
		params = getCheckedIds();
		if(null == params || "" == params){
			infoMsg("请选择数据！");
			return false;
		}
	}
	if (arguments.length == 2) {
		if(null == params || "" == params){
			infoMsg("请选择数据！");
			return false;
		}
	}
	
	
	confirm("确认删除所选数据吗？",function(index){
		layer.close(index);
		url = url+ (url.indexOf("?")==-1?"?":"&")+params;
		
		var loadingIndexxxxxxx = layer.msg('正在执行删除..', {shade:0.00001,icon: 16,time: 1000*60*10 });
		$.ajax({type:"POST",url:url,dataType:"json",success:function(data){
					if(data.result){
						datagrid("datagrid");
						ShowSuccess(data.message);
					}else{
						ShowFailure(data.message);
					}
					
					if(data.func != undefined && "undefined" != data.func && data.func != null && data.func != ""){
		        		eval(eval(data.func));
		        	}
			},error:function(){
			   layer.close(loadingIndexxxxxxx);
			   errMsg("服务异常..");
			}});
	});
}

function prompt(title, callback){
  //prompt层
  layer.prompt({title: title, formType: 2}, callback);
}



function common(url,params,title,isConfirm, confirmType){
	if(confirmType == 'confirm'){
		confirm("确认进行【"+title+"】操作吗？",function(index){
			layer.close(index);
			url = url+ (url.indexOf("?")==-1?"?":"&")+params;
			
			var loadingIndexxxxxxx = layer.msg('正在执行'+title+"..", {shade:0.00001,icon: 16,time: 1000*60*10 });
			$.ajax({type:"POST",url:url,dataType:"json",success:function(data){
					if(data.result){
						if($(".datagrid").length > 0){
							datagrid("datagrid");
						}
						ShowSuccess(data.message);
					}else{
						ShowFailure(data.message);
					}
					
					if(data.func != undefined && "undefined" != data.func && data.func != null && data.func != ""){
		        		eval(eval(data.func));
		        	}
				   layer.close(loadingIndexxxxxxx);
				},error:function(){
				   layer.close(loadingIndexxxxxxx);
				   errMsg("服务异常..");
				}});
			
		});
	}else{
		prompt("确认【"+title+"】操作吗？输入操作原因",function(text, index){
			layer.close(index);
			url = url+ (url.indexOf("?")==-1?"?":"&")+params;
			url = url+ (url.indexOf("?")==-1?"?":"&")+"promptMsg="+text;
			var loadingIndexxxxxxx = layer.msg('正在执行'+title+"..", {shade:0.00001,icon: 16,time: 1000*60*10 });
			$.ajax({type:"POST",url:url,dataType:"json",success:function(data){
					if(data.result){
						datagrid("datagrid");
						ShowSuccess(data.message);
					}else{
						ShowFailure(data.message);
					}
					
					if(data.func != undefined && "undefined" != data.func && data.func != null && data.func != ""){
		        		eval(eval(data.func));
		        	}
				   layer.close(loadingIndexxxxxxx);
				},error:function(){
				   layer.close(loadingIndexxxxxxx);
				   errMsg("服务异常..");
				}});
		});
	}
	
	
}


function dialog(title,url,width,height){
	//iframe层
	  layer.open({
	    type: 2,
	    title: title,
	    shadeClose: false,
	    maxmin:true,
	    shade: 0.7,
	    offset : ['50px'],
	    area: [width, height],
	    content: url, //iframe的url
	    end:function(){
	    	if($("#formtag").length>0){
	    		if($("#datagrid").length > 0){
		    		datagrid("datagrid");
		    	}
		    	
			    var datagridIdx = "datagrid";
			    if($("iframe").contents().find("#"+datagridIdx).length > 0){
				  $("#iframe")[0].contentWindow.datagrid(datagridIdx);
			    }
	    	}
	    }
	  }); 
  }

/***
 * 通过ajax验证通过后方可打开dialog
 * @param validateUrl   ajax请求路径
 * @param params        参数
 * @param url           dialog:url
 * @param title         dialog:title
 * @param width         dialog:width
 * @param height        dialog:height
 * @param isParent      dialog:isParent  是否父窗口打开
 * @returns
 */
function ajaxValidateForDialog(validateUrl,params,url,title,width,height,isParent){
	validateUrl = validateUrl+ (validateUrl.indexOf("?")==-1?"?":"&")+params;
	ajax(validateUrl,function(data){
		if(data.result){
			datagrid("datagrid");
			ShowSuccess(data.message);
			if(isParent){
				top.dialog(title,url,width,height);
			}else{
				dialog(title,url,width,height);
			}
		}else{
			ShowFailure(data.message);
		}
	});
}

function exports(url){
	var params = getCheckedIds();
	if(null != params && params.length > 0){
		url = url + (url.indexOf("?")==-1?"?":"&") + "ctype=2&" +params;
	}else{
		url = url + (url.indexOf("?")==-1?"?":"&") + "ctype=1&"+getSerializeParams();
	}
	window.open(url);
}

function getSerializeParams(){
	var datagrid = $("#datagrid");
	var queryForm = $(".queryForm[casedatagrid='datagrid']");
	var params = getArgsParams(datagrid).concat(getFormParams(queryForm));
	var sps = getSortsParams("datagrid");
	if(null != sps && sps.length>0){
		params = params.concat(sps);
	}
	if(null == params || params.length <= 0){
		return null;
	}
	var p = new Array();
	for(var i=0;i <params.length;i++){
		p.push(params[i].name+"="+params[i].value);
	}
	return p.join("&");
}


$(function(){
	$(".datagridSearch").click(function(){
		$(this).parent().submit();
	});
});